package com.googlecode.perfectable.visuable.renderer.widget;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ArrayNode;
import org.codehaus.jackson.node.ObjectNode;

import com.googlecode.perfectable.visuable.renderer.ElementRenderer;
import com.googlecode.perfectable.visuable.renderer.VisualRenderer;

public class WidgetElementRenderer implements ElementRenderer {
	private static final ObjectMapper MAPPER = new ObjectMapper();

	private static final String TAG_FIELD_NAME = "element-name";
	private static final String ATTRIBUTES_FIELD_NAME = "attributes";
	private static final String CHILDREN_FIELD_NAME = "children";
	private static final String TEXT_FIELD_NAME = "text";

	private final ObjectNode root;
	private final String elementName;
	private final ObjectNode attributes = MAPPER.createObjectNode();
	private final ArrayNode children = MAPPER.createArrayNode();
	private final StringBuilder textBuilder = new StringBuilder();

	public WidgetElementRenderer(ObjectNode root, String elementName) {
		this.root = root;
		this.elementName = elementName;
	}

	@Override
	public void attribute(String name, String value) {
		this.attributes.put(name, value);
	}

	@Override
	public void raw(String string) {
		this.textBuilder.append(string);
	}

	@Override
	public VisualRenderer children() {
		return new WidgetVisualRenderer(this.children);
	}

	@Override
	public void close() {
		this.root.put(TAG_FIELD_NAME, this.elementName);
		this.root.put(CHILDREN_FIELD_NAME, this.children);
		this.root.put(ATTRIBUTES_FIELD_NAME, this.attributes);
		this.root.put(TEXT_FIELD_NAME, this.textBuilder.toString());
	}

}
